package MyThread;

import sun.reflect.generics.tree.Tree;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: AliceMana
 * Date: 2023-01-01
 * Time: 14:09
 */

class Counter {
    public int count;

    // 加了 synchronized 之后, 进入方法就会加锁, 出了方法就会解锁
    // 如果两个线程同时尝试加锁, 此时, 一个能获取锁成功, 另一个只能阻塞等待 (BLOCKED)
    // 一直阻塞到刚才那个线程释放锁 (解锁), 当前线程才能加锁成功!!

    public void add() {
        synchronized (this) {
            count++;
        }
    }

    /*    synchronized public void add() {
        count++;
    }*/

}

public class ThreadDemo13 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();

        // 搞两个线程, 分别对 counter 调用 5w 次 add 方法
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });

        t1.start();
        t2.start();

        // 等待线程结束

        t1.join();
        t2.join();


        System.out.println("count = " + counter.count);
    }
}
